#!/usr/bin/env python
## dbui.py - The DrawBridge user interface
#
# @author Jeremiah Davis
# @author Killer Rabbit
#
# @date 2011
#
# @license BSD
#
# This is a prototype web interface for the DrawBridge system.
# It allows a user to choose a mote and sensors and times to
# get data.  It then displays it to the user.
# 
# This script should reside in the cgi-bin directory and have
# cgi enabled.  It is called by going to its url in a web browser.

import cgi
import sys

# for debugging
import cgitb
cgitb.enable()

sys.path.append('/home/tintaton/cs/seniorProject/wsn-toolkit/src/')

from DBMoteReader import DBMoteReader

db = DBMoteReader()
db.connectToDB()

form = cgi.FieldStorage()

## The mote chosen by the user
mote = form.getfirst('mote')

## The sensor chosen by the user
sensor = form.getfirst('sensor')

## The time to start getting data
starttime = form.getlist('stime')

## The time to end getting data
endtime = form.getlist('etime')

print '''\
Content-Type: text/html\n
<html><head><title>DrawBridge</title></head>
<body>
'''

## Motes to allow the user to choose from
motes = db.getMotes()

## This section of code prints the mote selection

print '''\
<p>Welcome to the DrawBridge system.</p>
<form name="choose_mote" action="./dbui.py" method=post>
<label>
Please choose a mote:
<select name="mote">
'''

for m in motes:
    if ( mote != None and int(mote) == m[0] ):
        print '<option value=%d selected>%s</option>' % m
    else:
        print '<option value=%d>%s</option>' % m
print '</label>'

## This section of code prints the sensor selection

if ( mote != None ):
    sensors = db.getSensors(int(mote))
    print '''\
<hr>
<label>
Please choose a sensor:
<select name="sensor">
'''
    for s in sensors:
        if ( sensor != None and str(sensor) == s[0] ):
            print '<option value="%s" selected>%s</option>' % (s[0],s[1])
        else:
            print '<option value="%s">%s</option>' % (s[0],s[1])
    print '</label>'

## This section of code prints the time selection
    if ( sensor != None ):
        #ensor = sensor prolly need to clean this stuff
        print '''\
<hr>
<label>
Please choose a start year:
<select name="stime">
'''
        year = 2010
        for i in range(3):
            if (len(starttime) > 0 and int(starttime[0]) == i):
                print '<option value=0 selected>Now</option>'
            elif (len(starttime) > 0 and int(starttime[0]) == i + year):
                print '<option value=%d selected>%d</option>' % (i+year, i+year)
            elif (i == 0):
                print '<option value=0>Now</option>'
            else :
                print '<option value=%d>%d</option>' % (i+year, i+year)

        print '''\
</select>
</label>
'''
        if (len(starttime) > 0 and int(starttime[0]) != 0 ):
            # Months
            print '''\
<br>
<label>
Please choose a start month:
<select name="stime">
'''
            months = ('January', 'February', 'March', 'April', 'May', 'June',
                      'July', 'August', 'September', 'October', 'November',
                      'December')
            for i in range(12):
                if (len(starttime) > 1 and int(starttime[1]) == i+1):
                    print '<option value=%d selected>%s</option>' % (i+1,months[i])
                else:
                    print '<option value=%d>%s</option>' % (i+1, months[i])
            
            print '''\
</select>
</label>
'''
            if (len(starttime) > 1):
                # Days
                print '''\
<br>
<label>
Please select a start day:
<select name="stime">
'''

                if int(starttime[1]) == 2: # February
                    if int(starttime[0]) % 400 == 0:
                        days = 29
                    elif int(starttime[0]) % 100 == 0:
                        days = 28
                    elif int(starttime[0]) % 4 == 0:
                        days = 29
                    else:
                        days = 28
                elif int(starttime[1]) in (4, 6, 9, 11):
                    days = 30
                else:
                    days = 31

                for i in range(1,days+1):
                    if len(starttime) > 2 and int(starttime[2]) == i:
                        print '<option value=%d selected>%d</option>' % (i,i)
                    else:
                        print '<option value=%d>%d</option>' % (i,i)

                print '''\
</select>
</label>
'''
                # Hours
                print '''\
<br>
<label>
Please select a start hour:
<select name="stime">
'''
                for i in range(24):
                    if ( len(starttime) > 3 and int(starttime[3]) == i):
                        print '<option value=%d selected>%d</option>' % (i,i)
                    else:
                        print '<option value=%d>%d</option>' % (i,i)
                print '''\
</select>
</label>
'''
                # Minutes
                print '''\
<br>
<label>
Please enter a start minute:
<select name="stime">
'''
                for i in range(60):
                    if ( len(starttime) > 4 and int(starttime[4]) == i):
                        print '<option value=%d selected>%d</option>' % (i,i)
                    else:
                        print '<option value=%d>%d</option>' % (i,i)

                print '''\
</select>
</label>
'''
                # Seconds
                print '''\
<br>
<label>
Please enter a start second:
<select name="stime">
'''
                for i in range(60):
                    if ( len(starttime) > 5 and int(starttime[5]) == i):
                        print '<option value=%d selected>%d</option>' % (i,i)
                    else:
                        print '<option value=%d>%d</option>' % (i,i)

                print '''\
</select>
</label>
'''
################################################################################
                # Now do this for end times
                print '''\
<hr>
<label>
Please choose an end year:
<select name="etime">
'''
                for i in range(3):
                    if (len(endtime) > 0 and int(endtime[0]) == i):
                        print '<option value=0 selected>Now</option>'
                    elif (len(endtime) > 0 and int(endtime[0]) == i + year):
                        print '<option value=%d selected>%d</option>' % (i+year, i+year)
                    elif (i == 0):
                        print '<option value=0>Now</option>'
                    else :
                        print '<option value=%d>%d</option>' % (i+year, i+year)

                print '''\
</select>
</label>
'''
                if (len(endtime) > 0 and int(endtime[0]) != 0 ):
                    # Months
                    print '''\
<br>
<label>
Please choose an end month:
<select name="etime">
'''
                    months = ('January', 'February', 'March', 'April', 'May', 'June',
                              'July', 'August', 'September', 'October', 'November',
                              'December')
                    for i in range(12):
                        if (len(endtime) > 1 and int(endtime[1]) == i+1):
                            print '<option value=%d selected>%s</option>' % (i+1,months[i])
                        else:
                            print '<option value=%d>%s</option>' % (i+1, months[i])
            
                    print '''\
</select>
</label>
'''
                    if (len(endtime) > 1):
                        # Days
                        print '''\
<br>
<label>
Please select an end day:
<select name="etime">
'''

                        if int(endtime[1]) == 2: # February
                            if int(endtime[0]) % 400 == 0:
                                days = 29
                            elif int(endtime[0]) % 100 == 0:
                                days = 28
                            elif int(endtime[0]) % 4 == 0:
                                days = 29
                            else:
                                days = 28
                        elif int(endtime[1]) in (4, 6, 9, 11):
                            days = 30
                        else:
                            days = 31

                        for i in range(1,days+1):
                            if len(endtime) > 2 and int(endtime[2]) == i:
                                print '<option value=%d selected>%d</option>' % (i,i)
                            else:
                                print '<option value=%d>%d</option>' % (i,i)
                            
                        print '''\
</select>
</label>
'''
                        # Hours
                        print '''\
<br>
<label>
Please select a start hour:
<select name="etime">
'''
                        for i in range(24):
                            if ( len(endtime) > 3 and int(endtime[3]) == i):
                                print '<option value=%d selected>%d</option>' % (i,i)
                            else:
                                print '<option value=%d>%d</option>' % (i,i)
                        print '''\
</select>
</label>
'''
                        # Minutes
                        print '''\
<br>
<label>
Please enter an end minute:
<select name="etime">
'''
                        for i in range(60):
                            if ( len(endtime) > 4 and int(endtime[4]) == i):
                                print '<option value=%d selected>%d</option>' % (i,i)
                            else:
                                print '<option value=%d>%d</option>' % (i,i)

                        print '''\
</select>
</label>
'''
                        # Seconds
                        print '''\
<br>
<label>
Please enter an end second:
<select name="etime">
'''
                        for i in range(60):
                            if ( len(endtime) > 5 and int(endtime[5]) == i):
                                print '<option value=%d selected>%d</option>' % (i,i)
                            else:
                                print '<option value=%d>%d</option>' % (i,i)
                            
                        print '''\
</select>
</label>
'''
##################################################################################
                # End of the end time select
print '''\
<input type="submit" value="Submit"/>
</select>
</form>
'''
#################################################################################
                # Now give the data, somehow!
from datetime import datetime

data = None

if ( len(starttime) > 0 and int(starttime[0]) == 0 ):
    data = db.getSensorData(sensor, int(mote))
elif (len(starttime) == 6 ):
    stime = datetime(int(starttime[0]), int(starttime[1]), int(starttime[2]), 
                     int(starttime[3]), int(starttime[4]), int(starttime[5]))
    if ( len(endtime) > 0 and int(endtime[0]) == 0 ):
        data = db.getSensorData(sensor, int(mote), stime)
    elif len(endtime) == 6:
        etime = datetime(int(endtime[0]), int(endtime[1]), int(endtime[2]), 
                     int(endtime[3]), int(endtime[4]), int(endtime[5]))
        data = db.getSensorData(sensor, int(mote), stime, etime)

print '<hr>'

if (data != None):
    print '''\

<p>
All our data are belong to you.
</p>
'''
#    print str(data)
    import os
    os.environ['HOME'] = '/home/tintaton/cs/python/tmp'

    import jddbplot
    print '<img src="data:image/png;base64,',

    jddbplot.plot(data[:])


    print '" alt="graph">'


print '''\
<hr>
<p>
The Drawbridge system was written by Jeremiah Davis, Bretton Murphy, and \
David Salas.&nbsp; Copyright 2011.  It is released under the modified BSD
License.&nbsp; The source for this project can be found at \
<a href="http://code.google.com/p/wsn-toolkit/>Google Code</a>.
</p>
</body></html>
'''


db.disconnectDB()
